"""
通知测试结果的方法
"""

import requests
from config import qkey,emailConfig
from loguru import logger 
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart



def qiyeWeixin(msgtype,media_id=None,content=None):
    """
    给企业微信发送通知
    """
    url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={qkey}"
    method = "post"
    if msgtype == "file":
        data = {
            "msgtype": "file",
            "file": {
                "media_id": media_id
            }
        }
    else:
        data = {
        "msgtype": "text",
        "text": {
            "content": content
        }
        }
    r = requests.request(method,url,json=data)
    logger.info(f"企业微信发送结果:{r.text}")



def uploadToQW(filePath):
    """
    上传附件到企业微信中
    """
    url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={qkey}&type=file"
    method = "post"
    data = {"media":open(filePath,"rb")}
    r = requests.request(method,url,files=data)
    # {"errcode":0,"errmsg":"ok","type":"file","media_id":"3e9n94LAUCtwasZp-m8WEQEtmJ4JhW8PpSFi5qB3MfmUhFoKyREhMzGpnSSX-xjsT","created_at":"1676710555"}
    return r.json()["media_id"]



def sendEmail(receivers,filePath,reportName="testReport.html"):
    """
    给指定的人发送邮件
    """
    sender = emailConfig["email_address"]
    receivers = receivers

    message = MIMEMultipart()
    files = MIMEText(open(filePath,"rb").read(),'base64','utf-8')
    files["Content-Type"] = 'application/octet-stream'
    files["Content-Disposition"] = f'attachment; filename="{reportName}"'
    message.attach(files)
    message.attach(MIMEText("测试完成，请查收测试报告",'plain','utf-8'))

    message['From'] = Header("浪晋",'utf-8')
    message['To'] = Header("收件人",'utf-8')
    message['Subject'] = Header("测试报告",'utf-8')
    try:
        smtpObj = smtplib.SMTP()
        smtpObj.connect("smtp.163.com",25)
        smtpObj.login(emailConfig["email_address"],emailConfig["key"])
        smtpObj.sendmail(sender,receivers,message.as_string())
        logger.info("邮件发送结果:邮件发送成功")
    except smtplib.SMTPException:
        logger.error("邮件发送结果:邮件发送失败")